#!/usr/bin/env python
# -*- coding: utf-8 -*-

'''
鉴权模块
'''

from lib.validate import Filter
from common.myconfig import CONF

SESSION_LEVEL = {
        'visitor': 0,
        'user': 1}


def method(method_list):
    '鉴别请求方法，传入一个字符串或列表、元组'
    def dec(func):
        '新装饰器'
        def _dec(self, *args, **kwargs):
            '新函数'
            req_method = self._request['REQUEST_METHOD'].lower()
            if req_method not in method_list:
                return self.error('forbidden')
            else:
                return func(self, *args, **kwargs)
        return _dec
    return dec


class SessionCheckError(Exception):
    '鉴权失败抛出的异常'
    pass


def session(session_level):
    '鉴别session，传入一个业务要求的鉴权等级'
    def dec(func):
        '新装饰器'
        def _dec(self, *args, **kwargs):
            '新函数'
            import urllib
            from lib.sqldata import ModelSession
            from common.mydata import ModelUser
            from common.myvalidate import ValidatorCommon

            sn_num = self._request.get_cookie(CONF['sn_name'])

            try:
                # 检查sn
                if not ValidatorCommon.check(sn_num, 'session_id'):
                    raise SessionCheckError

                # 获取Session数据
                mod_ss = ModelSession()
                session_info = mod_ss.get_session_info(sn_num)
                if not session_info:
                    raise SessionCheckError

                # 获取用户数据
                mod_usr = ModelUser()
                user_info = mod_usr.select_by_id(session_info['user_id'])
                if not user_info:
                    raise SessionCheckError

                self._session = {}
                self._session['sn'] = sn_num
                self._session['token'] = session_info['token']
                self._session['user_info'] = user_info
                self._render.view['_session'] = self._session

                return func(self, *args, **kwargs)
            except SessionCheckError:
                # 如果只需要游客权限，则可以继续
                if session_level == SESSION_LEVEL['visitor']:
                    self._render.view['_session'] = {}
                    return func(self, *args, **kwargs)
                else:
                    path = urllib.quote(self._request.req_uri)
                    self._render.view['path'] = path
                    return self.error('unauth')

        return _dec
    return dec


def token(func):
    '检查token是否正确'
    def dec(self, *args, **kwargs):
        '新函数'
        from common.myvalidate import ValidatorCommon

        form = self._request.form
        token_num = form.get('token', '')
        if not ValidatorCommon.check(token_num, 'token'):
            return self.error('token_notfound')
        if token_num != self._session['token']:
            return self.error('token_notmatch')
        return func(self, *args, **kwargs)
    return dec


def https(func):
    '检查是否使用https进行请求'
    def dec(self, *args, **kwargs):
        '新函数'
        scheme = self._request['wsgi.url_scheme'].lower()
        if scheme != 'https':
            return self.error('not_https')
        return func(self, *args, **kwargs)
    return dec
